import $http from '@/utils/x-request';
import $tools from '@/utils/x-tools';
import { $XTrack } from '@/report';

export default {
  namespaced: true,
  state: {
    // 设备信息
    windowInfo: uni.getWindowInfo() || {},
    // 0关闭，1半打开，2全打开
    openProduct: 0,
    // 页面详情
    pageDetail: null,
    // 页面模块
    pageModule: null,
    // 资源模块
    resourceModule: null,
    // 商品详情
    productDetail: null,
    // 服务承诺
    safeguardList: [],
    // 跑马灯标题
    carouselTitle: null,
    // 跑马灯数据
    carouselList: null,
    // 当前商品关联的所有优惠券列表，已领取和可领取，支持单个领取的
    couponList: null,
    // 当前商品关联的可领取优惠券数据，只支持批次领取，最多10个
    couponSend: null,
    // 用户当前选择的优惠券信息
    userSelectCoupon: null,
    // 当前是否领取过优惠券
    isSendCoupon: false,
    // 是否主动关闭过领取优惠券弹出层
    isCancelCoupon: false,
    // 店铺主页限制优惠的链接
    reLaunchUrl: null,
    // 首页限制优惠的链接
    homeReLaunchUrl: null,
    // 主推荐商品页面id
    primaryPageId: null,
    // 缓存当前选择的套餐及规格
    userSelectSku: null
  },
  mutations: {
    SET_DATA: (state, data) => {
      for (const key in data) {
        state[key] = data[key];
      }
    }
  },
  actions: {
    setData({ commit }, data) {
      return new Promise((resolve, reject) => {
        commit('SET_DATA', data);
        resolve();
      });
    },
    // 重置部分数据
    reset({ commit }) {
      return new Promise((resolve, reject) => {
        commit('SET_DATA', {
          pageDetail: null,
          pageModule: null,
          safeguardList: [],
          resourceModule: null,
          productDetail: null,
          primaryPageId: null,
          reLaunchUrl: null,
          homeReLaunchUrl: null,
          userSelectCoupon: null,
          isSendCoupon: false,
          isCancelCoupon: false
        });
        resolve();
      });
    },
    // 获取页面详情
    getPageDetail({ commit, dispatch, state, rootGetters }, params) {
      return new Promise((resolve, reject) => {
        // 获取页面详情请求参数中增加广告相关参数
        const systemInfo = uni.getSystemInfoSync(); // 设备系统信息
        const options = params;
        try {
          const { clickid, adid, creativeid, gdt_vid, wx_aid, weixinadinfo, ksUnitId, callback, ksCampaignId, ksCreativeId, ksSiteAccountId, pageId, hq_vid } = rootGetters.pageQuery || {};
          Object.assign(options, {
            adid,
            wx_aid,
            clickid,
            gdt_vid,
            creativeid,
            weixinadinfo,
            hq_vid,
            callback,
            ksUnitId,
            ksCampaignId,
            ksCreativeId,
            ksSiteAccountId,
            promotionDevice: systemInfo?.system,
            pageUrl: params.pageUrl ? params.pageUrl : null
          });
          $XTrack('isPageRequestPageId', {
            pageQuery: rootGetters.pageQuery,
            params
          });
          // 如果通过transit记录的页面id与当前请求的页面id不相符，那么停止此次请求
          console.log('匹配pageId 1', params.source, pageId, params.pageId, params.pageUrl);
          if (['stay', 'groups', undefined].includes(params.source) && pageId && pageId !== params.pageId) {
            return false;
          }
        } catch (e) {
          console.warn(e);
        }

        $http({
          login: true,
          alarm: true,
          error: false,
          url: '/product/page/app/detail',
          method: 'get',
          data: options
        }).then((res) => {
          // 页面数据
          const detail = res.data || null;
          // 页面模块
          let pageModule = null;
          // 页面资源模块
          let resourceModule = null;
          // 格式化页面数据
          if (detail) {
            // 页面模块
            const moduleList = detail.moduleList ? detail.moduleList : [];
            const moduleTrack = {
              pageId: options.pageId,
              list: []
            };
            pageModule = {};
            moduleList.forEach((v) => {
              const { moduleName, moduleStatus } = v;
              //  moduleStatus:  1显示 0隐藏
              if (v.moduleStatus === 1) {
                try {
                  const moduleData = JSON.parse(v.moduleData);
                  if (v.moduleName === 'exitPopup') {
                    // 单独处理挽留数据
                    moduleData.list = moduleData.list.map((item, index) => {
                      return {
                        ...item,
                        popupIndex: index,
                        moduleId: v.id
                      };
                    });
                    pageModule[v.moduleName] = moduleData;
                  } else if (v.moduleName === 'topPicks') {
                    // 删除关联的商品列表id，此数据不被使用，没必要存储
                    delete moduleData.pageIdList;
                    pageModule[v.moduleName] = moduleData;
                  } else {
                    pageModule[v.moduleName] = moduleData;
                  }

                  moduleTrack.list.push({
                    moduleName,
                    moduleStatus
                  });
                } catch (e) {
                  console.warn(`moduleList ${v.moduleNam} ->`, e);
                }
              }
            });
            $XTrack('pageModuleList', moduleTrack);

            // 跑马灯
            if (pageModule.marquee && !['1028', '1029'].includes(String(options.source))) {
              setTimeout(() => {
                dispatch('getRecentlyInfo', {
                  pageId: detail.id
                });
              }, 500);
            } else {
              // 重置跑马灯数据
              commit('SET_DATA', {
                carouselTitle: null,
                carouselList: null
              });
            }

            // 页面资源
            const resourceList = detail.resourceList ? detail.resourceList : [];
            resourceModule = {};
            resourceList.forEach((v) => {
              //  moduleStatus:  1显示 0隐藏
              if (v.resourceContent) {
                try {
                  const resourceContent = JSON.parse(v.resourceContent);
                  if (resourceModule[v.resourceType]) {
                    if (v.resourceType === 'detailPic') {
                      // 商品图文详情是存在多个模块内容的，需要把数据进行合并
                      resourceModule[v.resourceType].picList.push(...(resourceContent.picList || []));
                    }
                  } else {
                    resourceModule[v.resourceType] = resourceContent;
                  }
                } catch (e) {
                  console.warn(`resourceList ${v.resourceType} ->`, e);
                }
              }
            });
            // 移除原始数据
            delete detail.moduleList;
            delete detail.resourceList;
            detail.pageId = detail.id;

            const stateData = {
              pageModule,
              resourceModule,
              pageDetail: detail,
              primaryPageId: [1028, 1029, 1030].includes(Number(params.source)) ? state.primaryPageId : pageModule?.topPicks?.primaryPageId
            };
            $XTrack('GetPageDetail', {
              pageId: params.pageId,
              productId: detail.productId
            });
            commit('SET_DATA', stateData);
            resolve(stateData);
          } else {
            resolve({
              pageDetail: {
                pageStatus: 2
              }
            });
          }
        }).catch((err) => {
          reject(err);
        });
      });
    },
    // 获取商品详情
    getProductDetail({ commit, rootGetters }, params) {
      return new Promise((resolve, reject) => {
        try {
          const { pageId } = rootGetters.pageQuery || {};
          $XTrack('isPageRequestProductId', {
            pageQuery: rootGetters.pageQuery,
            params
          });
          // 如果通过transit记录的页面id与当前请求的页面id不相符，那么停止此次请求
          console.log('匹配pageId 2', params.source, pageId, params.pageId);
          if (['stay', 'groups', undefined].includes(params.source) && pageId && pageId !== params.pageId) {
            return false;
          }
        } catch (e) {
          console.warn('getProductDetail->', e);
        }
        $http({
          login: true,
          alarm: true,
          error: false,
          url: '/product/page/product/app/detail',
          method: 'get',
          data: params
        }).then((res) => {
          // 商品数据
          const detail = res.data || null;
          // 服务承诺
          const safeguardList = [];
          // 格式化商品数据
          if (detail) {
            // skuMode 规格模式：1-统一规格；2-多规格；3-套餐模式
            const { productSkus, skuMode, productComboList } = detail || {};
            if ([2, 3].includes(skuMode)) {
              let comboSkuInfo;
              let productSkuInfo;
              let productSkuList;
              // 格式化多规格 sku数据
              if (skuMode === 2) {
                const { skuInfo, skuList } = $tools.formatSku(productSkus);
                productSkuInfo = skuInfo;
                productSkuList = skuList;
              } else if (skuMode === 3) {
                // 格式化套餐数据
                comboSkuInfo = productComboList.map(item => {
                  const { id, comboName, comboSellingPoint, productSku } = item;
                  const { skuInfo, skuList } = $tools.formatSku(productSku);
                  return {
                    id,
                    comboName,
                    comboSellingPoint,
                    skuInfo,
                    skuList
                  };
                });
                // 默认使用第一个套餐数据
                const { skuList, skuInfo } = comboSkuInfo[0];
                productSkuInfo = skuInfo;
                productSkuList = skuList;
              }

              // console.log(comboSkuInfo);
              Object.assign(detail, {
                comboSkuInfo,
                productSkuInfo,
                productSkuList
              });
            }

            const productSafeguard = detail.productSafeguard ? detail.productSafeguard : null;
            try {
              if (productSafeguard) {
                if (productSafeguard.deliveryTypeText) {
                  const deliveryTypeText = JSON.parse(productSafeguard.deliveryTypeText);
                  deliveryTypeText.forEach((item) => {
                    safeguardList.push(item);
                  });
                }
                if (productSafeguard.productPromiseText) {
                  const productPromiseText = JSON.parse(productSafeguard.productPromiseText);
                  productPromiseText.forEach((item) => {
                    safeguardList.push(item);
                  });
                }
                if (productSafeguard.promiseAfterText) {
                  const promiseAfterText = JSON.parse(productSafeguard.promiseAfterText);
                  promiseAfterText.forEach((item) => {
                    safeguardList.push(item);
                  });
                }
                // 极速退款
                if (productSafeguard.autoRefundText) {
                  safeguardList.push(JSON.parse(productSafeguard.autoRefundText));
                }
                detail.groupMode = productSafeguard.groupMode;
              }
            } catch (e) {
              console.warn('getProductDetail->', e);
            }
            // 商品评价标签
            detail.commentLabelSelected = productSafeguard.commentLabelSelected || [];
            detail.productComment = productSafeguard.productComment;
          }

          // 移除原始数据，sku较多时，原始数据过于庞大，会使页面变卡
          delete detail.productSkus;
          delete detail.specInfo;
          delete detail.productComboList;

          const stateData = {
            productDetail: detail,
            safeguardList
          };
          commit('SET_DATA', stateData);
          resolve(stateData);
        }).catch((err) => {
          reject(err);
        });
      });
    },
    //
    // 获取跑马灯信息
    getRecentlyInfo({ commit }, params) {
      return new Promise((resolve, reject) => {
        $http({
          login: true,
          url: '/order/order/iu/recently/info',
          // url: 'https://yapi.madaomall.com/mock/170/order/order/iu/recently/info',
          method: 'get',
          report: false,
          data: params
        }).then((res) => {
          try {
            const data = res.data || null;
            commit('SET_DATA', {
              carouselTitle: null,
              carouselList: null
            });
            // 大于10分数据才展示
            if (data && data.recentlyOrderVo && data.recentlyOrderVo.length >= 10) {
              const list = data.recentlyOrderVo.map((item) => {
                const { avatarMarqueeUrl, userName, productSku } = item;
                const desc = [];
                if (productSku) {
                  desc.push('购买了');
                  const skuInfo = JSON.parse(productSku);
                  desc.push(skuInfo.join(','));
                }
                return {
                  ...item,
                  avatar: avatarMarqueeUrl,
                  name: userName,
                  desc: desc.join(''),
                  time: Math.floor(Math.random() * 9) + 1
                };
              });

              const value = {
                carouselTitle: `${data.pv}人正在浏览`,
                carouselList: list
              };
              commit('SET_DATA', value);
              resolve(value);
            }
          } catch (e) {
            console.log('获取跑马灯信息-> ', e);
          }
        });
      });
    },
    // 获取商品可使用的优惠券
    getCouponList({ commit, state }, opts) {
      return new Promise((resolve, reject) => {
        const { storeId, productId } = opts || {};
        const { pageId, source, gdt_vid, adid, discountAmount, scheme, state, ksUnitId, hq_vid } = opts?.query || {};
        const { query } = wx.getLaunchOptionsSync();
        const gdtVid = gdt_vid || adid || ksUnitId || hq_vid || query?.gdt_vid || query?.adid || query?.ksUnitId || query?.hq_vid || ['toutiao', 'kuaishou'].includes(scheme) || state === 'kuaishou';
        const params = {
          storeId,
          productId,
          pageId,
          gdtVid: null
        };
        // createdType 0-手动创建；1-自动快捷创建
        // 旧版本，直接获取用户可使用的优惠券数据
        // 新版本，只有通过卡包进入并且createdType === 0 才去获取用户可使用的优惠券数据
        // 其他情况下，直接返回空
        // 如果有广告id是需要带上
        if (gdtVid && !['1004', '1009', '1018', '1019', '1025', '1028', '1029', '1030', '1031'].includes(String(source))) {
          params.gdtVid = gdtVid;
        }
        $http({
          url: '/marketing/user/coupon/list/for/product',
          method: 'get',
          login: true,
          error: false,
          report: true,
          data: params
        }).then((res) => {
          const list = res.data ? res.data : [];
          $XTrack('onUserCouponReady', {
            ids: list.map(item => item.userCouponId)
          });
          const couponList = list.filter((item) => {
            // 挽留状态下，并且query中有优惠金额值的，去匹配对应金额的优惠券
            if (['stay', 'groups', '1023'].includes(source) && discountAmount) {
              return item.couponAmount === Number(discountAmount);
            } else {
              return true;
            }
          }).filter((item) => {
            // 通过卡包进入并且有优惠金额时，只匹配与优惠金额相等的券
            return ['1008'].includes(source) && discountAmount ? item.couponAmount === Number(discountAmount) : true;
          }).map((item) => {
            return {
              ...item,
              couponValidity: `${item.startedAt}至${item.expiredAt}`
            };
          });
          console.log('可被使用的优惠券->', couponList);
          commit('SET_DATA', {
            couponList: couponList
          });
          resolve(couponList);
        }).catch(() => {
          commit('SET_DATA', {
            couponList: null
          });
          reject(null);
        });
      });
    },
    // 当前商品关联的可领取优惠券，只支持批次领取，最多10个
    getCouponSendList({ commit }, params) {
      return new Promise((resolve, reject) => {
        $http({
          login: true,
          url: '/marketing/coupon/app/list/forall',
          method: 'get',
          error: false,
          report: false,
          data: params
        }).then((res) => {
          const couponSend = res.data ? res.data : null;
          commit('SET_DATA', {
            couponSend
          });
          resolve(couponSend);
        }).catch(() => {
          commit('SET_DATA', {
            couponSend: null
          });
          reject(null);
        });
      });
    },
    // 通知服务端优惠券领取成功
    setCouponSend({ commit }, detail) {
      return new Promise((resolve, reject) => {
        if (detail.errcode === 'OK') {
          const filter = detail?.send_coupon_result?.length ? detail.send_coupon_result.filter(item => item.code === 'SUCCESS') : [];
          const couponList = filter ? filter.map(item => {
            return {
              stockId: item.stock_id,
              couponCode: item.coupon_code
            };
          }) : [];
          if (couponList.length) {
            $http({
              login: true,
              url: '/marketing/user/coupon/save/batch',
              method: 'post',
              error: false,
              data: {
                couponList
              }
            }).then(() => {
              resolve(couponList);
            }).catch(() => {
              reject();
            });
          } else {
            reject();
          }
        } else {
          reject();
        }
      });
    },
    // 分享统计
    setShareCount({ commit }, params) {
      return new Promise((resolve, reject) => {
        $http({
          url: '/product/share/save',
          method: 'POST',
          error: false,
          report: false,
          data: params
        }).then((res) => {
          resolve(res);
        });
      });
    },
    // 获取店铺信息，并且配置相关信息
    getStoreInfo({ commit, state }, params) {
      return new Promise((resolve, reject) => {
        $http({
          login: true,
          url: '/account/store/base/info',
          method: 'get',
          report: false,
          data: params
        }).then((res) => {
          const { homePageId, storeLevel, storeId } = res.data || {};
          const { source, pageId, sourcePageId } = params;
          // 没有配置好特推荐，店铺页不展示对应入口
          // 通过好物推荐页再进入时不进行配置
          if (state.primaryPageId && !['1028', '1029', '1030'].includes(source) && storeLevel > 0) {
            let reLaunchUrl;
            const query = $tools.object2param({
              id: homePageId,
              pageId,
              storeId,
              primaryPageId: state.primaryPageId,
              source: 1024
            });
            // 店铺首页配置
            if (homePageId) {
              reLaunchUrl = `/pages/decorate/index?${query}`;
            } else {
              reLaunchUrl = `/packages/store/index?${query}`;
            }
            commit('SET_DATA', {
              reLaunchUrl
            });
          } else {
            // 如果没有配置好特推荐，进行下一步链路，进入店铺首页
            let reLaunchUrl;
            const query = $tools.object2param({
              id: homePageId,
              pageId: sourcePageId || pageId,
              storeId,
              primaryPageId: state.primaryPageId,
              source: 1024
            });
            // 店铺首页配置
            if (homePageId) {
              reLaunchUrl = `/pages/decorate/index?${query}`;
            } else {
              reLaunchUrl = `/packages/store/index?${query}`;
            }
            commit('SET_DATA', {
              reLaunchUrl
            });
          }
          $XTrack('ProductStoreInfo', {
            storeId,
            homePageId,
            storeLevel,
            primaryPageId: state.primaryPageId
          });
          resolve(res);
        }).catch(() => {
          reject();
        });
      });
    },

    setSelectedSku({ commit }, params) {
      return new Promise((resolve, reject) => {
        commit('SET_DATA', {
          userSelectSku: params
        });
        resolve();
      });
    }
  }
};
